#ifndef MODBUSMANAGER_H
#define MODBUSMANAGER_H

#include <QObject>
#include <QModbusRtuSerialMaster>
#include <QTimer>
#include <QMap>
#include <QSet>
#include <QSerialPort>

class ModbusManager : public QObject
{
    Q_OBJECT
public:
    explicit ModbusManager(QObject* parent = nullptr);
    ~ModbusManager();

    bool startSimulation(const QString& serialPortName,
        int baudRate = 9600,
        int parity = QSerialPort::NoParity,
        int dataBits = QSerialPort::Data8,
        int stopBits = QSerialPort::OneStop);
    void stopSimulation();

    void writeCoil(int address, bool value);
    bool isRunning() const;

    // 添加/移除监控的线圈地址
    void addMonitoredCoil(int address);
    void removeMonitoredCoil(int address);
    void setMonitoredCoils(const QSet<int>& addresses);  // 批量设置
    void writeRegister(int address, quint16 value);  // 写入寄存器
    void reinitializeMonitoring();
    // 添加监控寄存器的方法
    void addMonitoredRegister(int address);
    void removeMonitoredRegister(int address);
    void setMonitoredRegisters(const QSet<int>& addresses);

Q_SIGNALS:
    void coilUpdated(int address, bool value);     // 从站数据更新
    void logMessage(const QString& msg);           // 日志
    // 寄存器更新信号
    void registerUpdated(int address, quint16 value);

private Q_SLOTS:
    void pollModbusCoils();
    // 寄存器轮询方法
    void pollModbusRegisters();
    // 处理线圈读取完成事件
    void onCoilReadFinished(QModbusReply* reply, int startAddress);
    // 处理寄存器读取完成事件
    void onRegisterReadFinished(QModbusReply* reply, int startAddress);

private:
    void sendReadCoilsRequest(int startAddress, int count);
    // 发送寄存器读取请求的辅助方法
    void sendReadRegistersRequest(int startAddress, int count);

private:
    QModbusClient* modbus_ = nullptr;
    QTimer* coilTimer_ = nullptr;
    bool isRunning_ = false;
    QMap<int, bool> coilValues_;
    // 寄存器轮询定时器
    QTimer* registerTimer_ = nullptr;
    QMap<int, qint16> registerValues_; // 存储寄存器值
    QSet<int> monitoredCoils_;         // 监控的线圈地址集合
    QMap<int, int> monitorCoilCounts_;  // 引用计数：地址，被多少组件引用
    QSet<int> monitoredRegisters_;         // 监控的寄存器地址集合
    QMap<int, int> monitorRegisterRefCounts_;  // 寄存器地址引用计数
};

#endif // MODBUSMANAGER_H
